/**
 * 
 */
package Commands;

import GPIO.GPIOControl;

/**
 * @author Jonas Spitzenpfeil
 * 
 */
public class PINSCmd extends Command {

	private boolean request = false;
	private String result = "";
	private boolean[] pinStates = new boolean[GPIOControl.getPinCount()];

	public PINSCmd() {
		commandString = "PINS";
	}

	@Override
	public void execute() throws Exception {
		if (request) {
			// Build state string
			result = "PINS ";
			int count = GPIOControl.getPinCount();
			for (int i = 0; i < count; i++) {
				int state = GPIOControl.getPinOut(i) ? 1 : 0;
				result = result.concat(String.valueOf(state) + ",");
			}

			// Remove leading comma
			result = result.substring(0, result.length() - 1);
		} else {
//			// Set the pin output
//			result = "";
//			for (int i = 0; i < GPIOControl.getPinCount(); i++) {
//				GPIOControl.setPinOut(i, pinStates[i]);
//			}
		}
	}

	@Override
	public void validateOptions(String options) {
		if (options.isEmpty()) {
			return;
		}

		// Check for request
		if (options.charAt(0) == '?') {
			request = true;
		} else {

			String[] splitted = options.split(",");

			if (splitted.length <= GPIOControl.getPinCount()) {

				// Loop through parameter list
				for (int i = 0; i < splitted.length; i++) {
					String s = splitted[i];
					pinStates[i] = (!s.isEmpty() && Integer.parseInt(s) == 1);
				}
			}
		}
	}

	@Override
	public String getResult() {
		String ret = result;
		result = "";
		return ret;
	}
}
